package com.lpgu.security.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lpgu.security.generator.domain.User;
import com.lpgu.security.generator.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.provisioning.UserDetailsManager;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @author gulup
 * createDate: 2025/2/12
 * description:
 */
@Component
public class DbUserManagerService implements UserDetailsService, UserDetailsManager {
    @Autowired
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUserNamer, username);
        List<User> userList = userService.list(queryWrapper);
        if (!userList.isEmpty()) {
            User user = userList.get(0);
            List<GrantedAuthority> list = new ArrayList<>();
            //授权，后期需要改为查询数据库动态获得用户拥有的权限和角色
            list.add(new SimpleGrantedAuthority("add"));
            list.add(new SimpleGrantedAuthority("delete"));
            list.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
            return new org.springframework.security.core.userdetails.User(user.getUserNamer(),
                    user.getPassword(), list);

        }

        return null;
    }

    @Override
    public void createUser(UserDetails user) {
        User userDb = new User();
        userDb.setUserNamer(user.getUsername());
        userDb.setPassword(user.getPassword());
        userService.save(userDb);
    }

    @Override
    public void updateUser(UserDetails user) {

    }

    @Override
    public void deleteUser(String username) {

    }

    @Override
    public void changePassword(String oldPassword, String newPassword) {

    }

    @Override
    public boolean userExists(String username) {
        return false;
    }
}
